package com.yami.shop.admin.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.Valid;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.JsonObject;
import com.yami.shop.bean.dto.ShopDetailSalesDto;
import com.yami.shop.bean.model.Agent;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.UserAndShop;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.*;
import com.yami.shop.sys.model.SysUser;
import com.yami.shop.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import com.baomidou.mybatisplus.core.metadata.IPage;

import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.ShopDetailParam;

import cn.hutool.core.util.StrUtil;
import ma.glasnost.orika.MapperFacade;



/**
 *
 * @author lgh on 2018/08/29.
 */
@Controller
@RequestMapping("/shop/shopDetail")
public class ShopDetailController {

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
	private MapperFacade mapperFacade;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AgentService agentService;

    @Autowired
	private SmsLogService smsLogService;

    @Autowired
	private OrderService orderService;

    @Autowired
	private CheckAccountService checkAccountService;



	/**
	 * 修改分销开关
	 */
	@PutMapping("/isDistribution")
	//@PreAuthorize("@pms.hasPermission('shop:shopDetail:update')")
	public ResponseEntity<Void> updateIsDistribution(@RequestParam Integer isDistribution){
		ShopDetail shopDetail=new ShopDetail();
		shopDetail.setShopId(SecurityUtils.getSysUser().getShopId());
		shopDetail.setIsDistribution(isDistribution);
		shopDetailService.updateById(shopDetail);
		// 更新完成后删除缓存
		shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId());
		return ResponseEntity.ok().build();
	}
	/**
	 * 获取信息
	 */
	@GetMapping("/info")
	@PreAuthorize("@pms.hasPermission('shop:shopDetail:info')")
	public ResponseEntity<ShopDetail> info(){
		ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(SecurityUtils.getSysUser().getShopId());
		return ResponseEntity.ok(shopDetail);
	}


	/**
	 * 分页获取--入驻审核
	 */
    @GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('shop:shopDetail:page')")
	public ResponseEntity<IPage<ShopDetail>> page(ShopDetail shopDetail,PageParam<ShopDetail> page){
		IPage<ShopDetail> shopDetails = shopDetailService.page(page,
				new LambdaQueryWrapper<ShopDetail>()
						.like(StrUtil.isNotBlank(shopDetail.getShopName()),ShopDetail::getShopName,shopDetail.getShopName())
						.like(StrUtil.isNotBlank(shopDetail.getShopAddress()),ShopDetail::getShopAddress,shopDetail.getShopAddress())
                        .eq(shopDetail.getState() != null, ShopDetail::getState, shopDetail.getState())
						.eq(shopDetail.getShopStatus() != null, ShopDetail::getShopStatus, shopDetail.getShopStatus())
						.eq(shopDetail.getShopId() != null, ShopDetail::getShopId, shopDetail.getShopId())
						.orderByDesc(ShopDetail::getShopId));
		return ResponseEntity.ok(shopDetails);
	}

	/**
	 * 分页获取--商家管理(只查询审核通过的商家)
	 */
	@GetMapping("/managePage")
//	@PreAuthorize("@pms.hasPermission('shop:shopDetail:managePage')")
	public ResponseEntity<IPage<ShopDetail>> managePage(ShopDetail shopDetail,PageParam<ShopDetail> page){
		IPage<ShopDetail> shopDetails = shopDetailService.page(page,
				new LambdaQueryWrapper<ShopDetail>()
						.like(StrUtil.isNotBlank(shopDetail.getShopName()),ShopDetail::getShopName,shopDetail.getShopName())
						.like(StrUtil.isNotBlank(shopDetail.getShopAddress()),ShopDetail::getShopAddress,shopDetail.getShopAddress())
						.eq(shopDetail.getState() != null, ShopDetail::getState, shopDetail.getState())
						.eq(shopDetail.getShopStatus() != null, ShopDetail::getShopStatus, shopDetail.getShopStatus())
						.eq(shopDetail.getShopId() != null, ShopDetail::getShopId, shopDetail.getShopId())
                        .eq(ShopDetail::getState,0)
						.orderByDesc(ShopDetail::getShopId));
		return ResponseEntity.ok(shopDetails);
	}

    /**
     * 商家入驻信息
     * @param userAndShop
     * @return
     */
    @PostMapping("/registerMerchantUser")
    @ApiOperation(value="商家入驻用户信息", notes="商家入驻用户信息")
    public ResponseEntity<String> registera(@RequestBody UserAndShop userAndShop) {
        String username = userAndShop.getUsername();
        SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username)
				.eq(SysUser::getMobile,userAndShop.getMobile())
		);
        if (dbUser!=null) {
            return ResponseEntity.badRequest().body("该用户已存在");
        }
        //向百度发送请求,获取经纬度
		UserAndShop userAndShop1 = GetCoordinates(userAndShop);
        String result = sysUserService.toSave(userAndShop1);
        //注册成功,向平台管理员发送信息
		ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(1l);
		smsLogService.sendSmsToAmdin(shopDetail.getMobile());
        return ResponseEntity.ok(result);
    }


    /**
     * 判断电话是否重复
     */
    @PostMapping("/checkPhone")
    public ResponseEntity<ShopDetail> checkPhone(@Param("mobile") String mobile){
        ShopDetail shopDetail = shopDetailService.selectByMobile(mobile);
        return ResponseEntity.ok(shopDetail);
    }

    /**
     * 判断身份证号是否重复
     */
    @PostMapping("/checkIdCard")
    public ResponseEntity<ShopDetail> checkIdCard(@Param("idCard") String idCard){
        ShopDetail shopDetail = shopDetailService.selectByIdCard(idCard);
        return ResponseEntity.ok(shopDetail);
    }

    /**
     * 获取信息
	 */
	@GetMapping("/info/{shopId}")
	@PreAuthorize("@pms.hasPermission('shop:shopDetail:info')")
	public ResponseEntity<ShopDetail> info(@PathVariable("shopId") Long shopId){
		ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
		// 店铺图片
		return ResponseEntity.ok(shopDetail);
	}

	/**
	 * 保存
	 */
	@PostMapping
	@PreAuthorize("@pms.hasPermission('shop:shopDetail:save')")
	public ResponseEntity<Void> save(@Valid ShopDetailParam shopDetailParam){
		ShopDetail shopDetail = mapperFacade.map(shopDetailParam, ShopDetail.class);
		shopDetail.setCreateTime(new Date());
		shopDetail.setShopStatus(1);
		shopDetailService.save(shopDetail);
		return ResponseEntity.ok().build();
	}

	/**
	 * 修改
	 */
	@PutMapping
//	@PreAuthorize("@pms.hasPermission('shop:shopDetail:update')")
	public ResponseEntity<String> update(@Valid ShopDetail shopDetail){
		ShopDetail daShopDetail = shopDetailService.getShopDetailByShopId(shopDetail.getShopId());
		shopDetail = mapperFacade.map(shopDetail, ShopDetail.class);
		shopDetail.setUpdateTime(new Date());
		shopDetailService.updateShopDetail(shopDetail,daShopDetail);
		return ResponseEntity.ok("success");
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('shop:shopDetail:delete')")
	public ResponseEntity<Void> delete(@PathVariable Long id){
		shopDetailService.deleteShopDetailByShopId(id);
		return ResponseEntity.ok().build();
	}

	/**
	 * 更新店铺状态
	 */
	@PutMapping("/shopStatus")
//	@PreAuthorize("@pms.hasPermission('shop:shopDetail:shopStatus')")
	public ResponseEntity<String> shopStatus(@RequestParam Long shopId,@RequestParam Integer shopStatus){
		String result = "success";
		ShopDetail shopDetail = new ShopDetail();
		shopDetail.setShopId(shopId);
		shopDetail.setShopStatus(shopStatus);
		shopDetailService.updateById(shopDetail);
		// 更新完成后删除缓存
		shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId());
		return ResponseEntity.ok(result);
	}

    /**
     * 获取供应商信息
     */
    @GetMapping("/AgentInfo")
//    @PreAuthorize("@pms.hasPermission('shop:shopDetail:info')")
    public ResponseEntity<List<Agent>> AgentInfo(){
        List<Agent> agentList = agentService.getAllMessage();
        // 店铺图片
        return ResponseEntity.ok(agentList);
    }

    /**
     * 更新店铺审核状态
     */
    @PutMapping("/shopState")
    @PreAuthorize("@pms.hasPermission('shop:shopDetail:shopState')")
    public ResponseEntity<Void> shopState(ShopDetail shopDetail){
       sysUserService.updateShopState(shopDetail);
        // 更新完成后删除缓存
        shopDetailService.removeShopDetailCacheByShopId(shopDetail.getShopId());
        return ResponseEntity.ok().build();
    }

    /**
     * 查询供应商辖区内的店铺
     */
    @GetMapping("/shopInfo")
    public ResponseEntity<List<ShopDetail>> shopInfo(Long agentId){
        List<ShopDetail> agentList = shopDetailService.selectByAgentId(agentId);
        return ResponseEntity.ok(agentList);
    }

	/**
	 * 获取所有的店铺名称
	 */
    @GetMapping("/listShopName")
	public ResponseEntity<List<ShopDetail>> listShopName(){
		List<ShopDetail> list = shopDetailService.list().stream().map((dbShopDetail) ->{
			ShopDetail shopDetail = new ShopDetail();
			shopDetail.setShopId(dbShopDetail.getShopId());
			shopDetail.setShopName(dbShopDetail.getShopName());
			return shopDetail;
		}).collect(Collectors.toList());
		return ResponseEntity.ok(list);
	}

	/**
	 * 获取店铺信息
	 */
	@GetMapping("/getShopDetailInformation")
	public ResponseEntity<ShopDetail> getShopDetailInformation(){
		Long shopId = SecurityUtils.getSysUser().getShopId();
		ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
		// 店铺图片
		return ResponseEntity.ok(shopDetail);
	}

    /**
     * 个人中心信息修改
     */
    @PutMapping("/updateInformation")
    public ResponseEntity<ShopDetail> updateInformation(ShopDetail shopDetail){
		Long shopId = SecurityUtils.getSysUser().getShopId();
		shopDetail.setShopId(shopId);
        shopDetailService.updateById(shopDetail);
        return ResponseEntity.ok(shopDetail);
    }

	/**
	 * 获取具体位置的经纬度
	 */
	@GetMapping("/GetCoordinates")
	public UserAndShop  GetCoordinates(UserAndShop userAndShop){
		//具体地址
		String shopAdress = userAndShop.getShopAddress().replace(" ","");
		//市
		String city = userAndShop.getCity().replace(" ","");
		//区
		String area = userAndShop.getArea();
		if(shopAdress!=null&&!"".equals(shopAdress)) {
			StringBuffer requestUrl = new StringBuffer("http://restapi.amap.com/v3/geocode/geo?key=478e8dad5f2572ec3ec7d7537153b9c2&s=rsv3&city=");
			requestUrl.append(city).append("&address=").append(area).append(shopAdress);
			HttpClient client = HttpClientBuilder.create().build();//构建一个Client
			HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
			HttpResponse response = null;//提交POST请求
			try {
				response = client.execute(post);
				HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
				String content = EntityUtils.toString(result);
				JSONObject json = new JSONObject(content);
				JSONArray jsonArray = json.getJSONArray("geocodes");
				JSONObject data =null;
				for(int i=0;i<jsonArray.length();i++){
					 	data = jsonArray.getJSONObject(i);
					    String location = (String) data.get("location");
					    if(location!=null){
					    	String [] address = location.split(",");
							String lng = address[0];
							String lat = address[1];
								userAndShop.setShopLng(String.valueOf(lng));
								userAndShop.setShopLat(String.valueOf(lat));
						}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return userAndShop;
	}


    /**
     * 修改营业时间
     */
    @PutMapping("/updateOpenTime")
    public ResponseEntity<ShopDetail> updateOpenTime(ShopDetail shopDetail){
        Long shopId = SecurityUtils.getSysUser().getShopId();
        shopDetail.setShopId(shopId);
        shopDetailService.updateById(shopDetail);
        return ResponseEntity.ok(shopDetail);
    }

	/**
	 * 获取同一法人的所有店铺
	 */
	@GetMapping("/getAllShopDetailByOnePerson")
	public ResponseEntity<List<ShopDetail>> getAllShopDetailByOnePerson(){
		Long shopId = SecurityUtils.getSysUser().getShopId();
		ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
		List<ShopDetail> shopDetailList =null;
		//当前店铺是主店的时候,查询所有的分店
		int mainStore = shopDetail.getMainStore();
		if(mainStore==0){
			shopDetailList = shopDetailService.getAllBranchStore(shopId);
			//设置登陆名称,根据登录名称
			String loginName = shopDetailService.getLoginName(shopId);
			shopDetail.setLoginName(loginName);
			shopDetailList.add(shopDetail);
		}else{
			//获取主店的信息
			ShopDetail mainShopDetail = shopDetailService.getShopDetailByShopId(Long.valueOf(mainStore));
			String loginName = shopDetailService.getLoginName(Long.valueOf(mainStore));
			mainShopDetail.setLoginName(loginName);
			if(mainShopDetail!=null){
				shopDetailList = shopDetailService.getAllBranchStore(mainShopDetail.getShopId());
				shopDetailList.add(mainShopDetail);
			}
		}
		return ResponseEntity.ok(shopDetailList);
	}

	/**
	 * 开分店
	 */
	@PostMapping("/openBranch")
	@ApiOperation(value="商家入驻用户信息", notes="商家入驻用户信息")
	public ResponseEntity<String> openBranch(@RequestBody UserAndShop userAndShop) {
		String username = userAndShop.getUsername();
		SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
				.eq(SysUser::getUsername, username)
				.eq(SysUser::getMobile,userAndShop.getMobile())
		);
		if (dbUser!=null) {
			return ResponseEntity.badRequest().body("该用户已存在");
		}
		//向百度发送请求,获取经纬度
		UserAndShop userAndShop1 = GetCoordinates(userAndShop);
		String result = sysUserService.saveBranchShop(userAndShop1);
		//注册成功,向平台管理员发送信息
		ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(1l);
		smsLogService.sendSmsToAmdin(shopDetail.getMobile());
		return ResponseEntity.ok(result);
	}

	/**
	 * 获取商家销售记录
	 */
	@GetMapping("/getShopSalesData")
	public ResponseEntity<List<ShopDetailSalesDto>> getShopSalesData(ShopDetailSalesDto shopDetailSalesDto, PageParam<Order> page){
		List<ShopDetailSalesDto> shopDetailSalesDtoList = new ArrayList<ShopDetailSalesDto>();
		IPage<ShopDetailSalesDto> shopDetailSalesDtoIPage;
		//使用年份 月份来查询对应的店铺数据
		if(shopDetailSalesDto.getStartTime()!=null&&shopDetailSalesDto.getEndTime()!=null){
			//根据指定的年月查询数据
			IPage<Order> orderIPage = orderService.getShopDetailIdByTime(shopDetailSalesDto,page);
			List<Order> orderList = orderIPage.getRecords();
			if(CollectionUtils.isNotEmpty(orderList)){
				for(Order order:orderList){
					Long shopId = order.getShopId();
					ShopDetailSalesDto shopDetailSalesDto1 = new ShopDetailSalesDto();
					ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
					//设置店铺名称
					shopDetailSalesDto1.setShopName(shopDetail.getShopName());
					//设置店主
					shopDetailSalesDto1.setShopKeeper(shopDetail.getShopOwner());
					//设置店主电话
					shopDetailSalesDto1.setTel(shopDetail.getMobile());
					//设置可提现金额
					shopDetailSalesDto1.setWithdrawalAmount(shopDetail.getCashMoney());
					//查询店铺销售额
					double salesVolume = orderService.getShopBusinessVolumeByTime(shopDetailSalesDto,shopId);
					shopDetailSalesDto1.setSalesVolume(salesVolume);
					//查询成交额
					double shopBusinessVolume = checkAccountService.getShopBusinessVolumeByTime(shopDetailSalesDto,shopId);
					shopDetailSalesDto1.setBusinessVolume(shopBusinessVolume);
					shopDetailSalesDtoList.add(shopDetailSalesDto1);
				}
			}
		}else{
			//获取商家ID
			IPage<Order> orderIPage = orderService.getShopDetailId(page);
			List<Order> orderList = orderIPage.getRecords();
			if(CollectionUtils.isNotEmpty(orderList)){
				for(Order order:orderList ){
					Long shopId = order.getShopId();
					ShopDetailSalesDto shopDetailSalesDto1 = new ShopDetailSalesDto();
					ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopId);
					//设置店铺名称
					shopDetailSalesDto1.setShopName(shopDetail.getShopName());
					//设置店主
					shopDetailSalesDto1.setShopKeeper(shopDetail.getShopOwner());
					//设置店主电话
					shopDetailSalesDto1.setTel(shopDetail.getMobile());
					//设置可提现金额
					shopDetailSalesDto1.setWithdrawalAmount(shopDetail.getCashMoney());
					//查询店铺销售额
					double salesVolume =  orderService.getShopSalesVolume(shopId);
					shopDetailSalesDto1.setSalesVolume(salesVolume);
					//查询成交额
					double shopBusinessVolume = checkAccountService.getShopBusinessVolume(shopId);
					shopDetailSalesDto1.setBusinessVolume(shopBusinessVolume);
					shopDetailSalesDtoList.add(shopDetailSalesDto1);
				}
			}
		}
		return ResponseEntity.ok(shopDetailSalesDtoList);
	}
}
